package me.zhengjie.utils;


import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.WriterException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class QRCodeUtil {

    public static BufferedImage createQRCode(String msg, Boolean useBack, Boolean useLogo, Boolean transparent) throws IOException, WriterException {
        // 这里的图片地址，支持网络图片，本地相对路劲图片，本地绝对路径图片
        String logo = "C:\\work\\codes\\backup\\logo.png";
        String leaf = "C:\\work\\codes\\backup\\leaf.png";//向右偏的叶子，用于左下和右上
        String leaf1 = "C:\\work\\codes\\backup\\leaf1.png";//向左偏的叶子，用于左上
        String bg = "C:\\work\\codes\\backup\\back.png";
        // 生成二维码，并输出为qr.png图片

        QrCodeGenWrapper.Builder builder = QrCodeGenWrapper.of(msg);
        float logoOpacity = 1f;
        if (useBack != null && useBack) {
            builder = builder.setBgImg(bg).setBgOpacity(0.7f);
            logoOpacity = 0.7f;
        }
        if (useLogo != null && useLogo) {
            builder = builder.setLogo(logo)
                    .setLogoStyle(QrCodeOptions.LogoStyle.NORMAL)
//                    .setLogoBgColor(0xfffefefe)
//                .setLogoBorderBgColor(0xffc7c7c7)
                    .setLogoBorder(false)
                    .setLogoRate(6);
//                    .setLogoOpacity(logoOpacity);
        }
        int bgColor = 0xffffffff;
        if (transparent && (useBack == null || !useBack)) {
            bgColor = 0x00ffffff;
        }
        builder = builder.setW(1500)
//                .setBgStyle(QrCodeOptions.BgImgStyle.PENETRATE)
//                .setBgW(500)
//                .setBgH(500)
                // 二维码着色点
                .setDrawPreColor(new Color(85, 138, 130))
                // 二维码背景图 取白色
                .setDrawBgColor(bgColor)
                .setLTDetectImg(leaf1)
                .setLDDetectImg(leaf)
                .setRTDetectImg(leaf)
                // 这个参数表示探测图形中的透明区域，用二维码背景色填充
                .setDiaphaneityFill(true)
                // 支持将临近相同的合并成一个大的圆点
//                .setDrawEnableScale(true)
                .setDrawStyle(QrCodeOptions.DrawStyle.CIRCLE);
        BufferedImage ans = builder.asBufferedImage();
//                .asFile("C:\\work\\codes\\backup\\qr.png");
        return ans;
    }

    public static void main(String[] args) {
        try {
            BufferedImage ans = QRCodeUtil.createQRCode("https://www.lvhe.cn", true, true, true);
            File outputfile = new File("C:\\work\\codes\\backup\\qr.png");
            ImageIO.write(ans,  "png",  outputfile);
            System.out.println("success");
        } catch (IOException | WriterException e) {
            throw new RuntimeException(e);
        }
    }
}
